//      client.c
//      
//      Copyright 2012 Piotr <piotr@piotr-dell>
//      
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU General Public License as published by
//      the Free Software Foundation; either version 2 of the License, or
//      (at your option) any later version.
//      
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU General Public License for more details.
//      
//      You should have received a copy of the GNU General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
//      MA 02110-1301, USA.


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#include "client.h"

char filein[10], fileout[10];
FILE *in, *out;

int main(int argc, char** argv)
{
	snprintf(filein,10,"%din", getpid());
	snprintf(fileout,10,"%dout", getpid());

	out = fopen(fileout, "a+");

	//deskryptory potoku
	int pipe_desc[2];
	fprintf(out,"Uruchomiono klienta!");
	if (argc != 3) {
		fprintf(out,"[E]Client: Niewłaściwa ilość argumentów\n");
		return DLM_ERR_UKNOWN;
	}
	
	sscanf(argv[1], "%d", &pipe_desc[PIPE_RECV]);
	sscanf(argv[2], "%d", &pipe_desc[PIPE_SEND]);
	
	DLM_init(pipe_desc);
	
	fprintf(out,"\nPodaj dane do pliku (pid)in w formacie int int int int\n");
	fprintf(out,"Gdzie pierwsza liczba oznacza numer zasobu, druga typ operacji, trzecia nr blokady a czwarta wartosc timeout\n");

	int _resource;
	reqType _request;
	lockType _lock;
	int _timeout;
	char charbuf[20];
	charbuf[0] = 0;
	

	fclose(out);
	
	while(1) {
		sleep(1);
		in = fopen(filein, "a+");
		fgets(charbuf, 20, in);
		fclose(in);
		char cmd[] = "rm ";
	    system(strcat(cmd, filein));
		if(charbuf[0] != 0) {
			sscanf(charbuf, "%d %d %d %d", &_resource, &_request, &_lock, &_timeout);
			processData(_resource, _request, _lock, _timeout);
		}
		for(int i=0; i<20;++i)
			charbuf[i] = 0;
	}
}
void processData(int resource_id, reqType requestType, lockType lock_type, int timeout) {
	out = fopen(fileout, "a+");
	switch(requestType) {
	case DLM_REQ_TRYLOCK:
		fprintf(out, "Client_trylock (%d): odpowiedz od DLM: %d\n", getpid(), DLM_trylock(resource_id, lock_type));
		break;
	case DLM_REQ_LOCK:
		fprintf(out, "Client_lock (%d): odpowiedz od DLM: %d\n", getpid(), DLM_lock(resource_id, lock_type, timeout));
		break;
	case DLM_REQ_UNLOCK:
		fprintf(out, "Client_unlock (%d): odpowiedz od DLM: %d\n", getpid(), DLM_unlock(resource_id));
		break;
	default:
		printf("error\n");
		fprintf(out, "Niewłaściwy typ żądania!");
		break;
    }
    fclose(out);
}
